from fastapi import APIRouter, Depends, HTTPException
from typing import List, Dict, Any
import json
import os

from app.models.text2sql import Text2SqlRequest, SqlResponse, EvaluationRequest, EvaluationResult, Q2SqlPair
from app.services.text2sql_service import generate_sql, evaluate_sql
from app.core.db_engine import query_documents
from app.core.config import settings

# 创建路由器
router = APIRouter()

# 生成SQL的端点
@router.post("/text2sql", response_model=SqlResponse, tags=["Text2SQL"])
async def convert_text_to_sql(request: Text2SqlRequest):
    try:
        print(f"Received request: {request}")
        # 调用服务生成SQL（添加await关键字）
        result = await generate_sql(request.question, request.context)
        return result
    except Exception as e:
        print(f"Error in text2sql: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# 评估SQL的端点
@router.post("/evaluate", response_model=EvaluationResult, tags=["评估"])
def evaluate_sql_query(request: EvaluationRequest):
    try:
        print(f"Received evaluation request: {request}")
        # 调用服务评估SQL
        result = evaluate_sql(request.question, request.generated_sql, request.expected_sql)
        return result
    except Exception as e:
        print(f"Error in evaluation: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# 获取相关文档的端点
@router.get("/documents", response_model=List[Dict[str, Any]], tags=["文档"])
async def get_relevant_documents(query: str, n_results: int = 5):
    try:
        print(f"Received documents request: query={query}")
        # 查询相关文档（添加await关键字）
        documents = await query_documents(query, n_results)
        return documents
    except Exception as e:
        print(f"Error in documents: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# 获取所有问题-答案对的端点
@router.get("/q2sql-pairs", response_model=List[Q2SqlPair], tags=["数据"])
def get_q2sql_pairs():
    try:
        print("Received q2sql-pairs request")
        # 读取q2sql_pairs.json文件（使用相对路径）
        base_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'sakila')
        q2sql_path = os.path.join(base_path, 'q2sql_pairs.json')
        
        if not os.path.exists(q2sql_path):
            raise FileNotFoundError(f"问题-答案对文件不存在: {q2sql_path}")
            
        with open(q2sql_path, 'r', encoding='utf-8') as f:
            pairs = json.load(f)
        return pairs
    except Exception as e:
        print(f"Error in q2sql-pairs: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# 健康检查端点
@router.get("/health", tags=["系统"])
async def health_check():
    return {"status": "healthy", "message": "RAG Text2SQL评估系统服务正常运行"}